# !/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Author : 大野
import json

from common.log import Log
from common.db_config import DB_Config
from common.extractsql import ExtractSql
import configparser
import projectPath as path

log = Log()
db = DB_Config()
es = ExtractSql()
config = configparser.ConfigParser()
config.read(path.projectPathUrl() + '/config/config.ini', encoding='utf-8')


class DataBase:
    def __init__(self):
        self.work_env = config.get('ENV', 'work_env')

    # 执行sql
    def executeSql(self, conn, sql, m):
        cursor = conn.cursor()
        if m == 'r':
            if len(sql) == 1:
                for ss in sql:
                    cursor.execute(ss)
                    data = cursor.fetchall()
                    return data
            elif len(sql) > 1:
                All = []
                for ss in sql:
                    cursor.execute(ss)
                    data = cursor.fetchall()
                    All.append(data)
                all = list(set([i for a in All for i in a]))
                return all
            else:
                log.error(f"异常信息：{sql}")

        elif m == 'w':
            log.info(f"操作SQL》》》》【{sql}】")
            try:
                for ss in sql:
                    cursor.execute(ss)
                    conn.commit()
                last_id = cursor.lastrowid
                log.info(f"执行条数:{sql}")
                return {"code": 1, "id": last_id}
            except Exception as e:
                log.error(f"sql执行异常:{e}")
                cursor.close()
                conn.rollback()
                return {"code":0,"msg":str(e)}
            finally:
                log.info("执行结束")

    def test_platform(self, sql, env='qa', m='r'):
        if self.work_env == 'localhost':
            conn = db.db_test_platform()
        else:
            conn = db.db_test_pord()
        result = self.executeSql(conn, sql, m)
        return result

# if __name__ == '__main__':
#     sql = ['select tb.mobile_key,tm.customer_id,tb.plat_dp_name,tb.shop_id,tb.tenant_id,tb.plat_code                     from t_m_mem_brand tb join t_r_shopid_mapping tm on tb.shop_id = tm.shop_id                     where tb.plat_dp_name = "CLASSY·KISS卡士旗舰店" and tm.plat_code="JOS" and tb.tenant_id = "qiushi6"']
#     print(DataBase().contrast(sql))
